package parallel.project.framework;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Utility class for writing and reading {@link Serializable} objects.
 * 
 * @author Adam Clayton
 * @author Larry Walters
 */
public class Serializer 
{
	/**
	 * Reads from the given file and returns the object read.  The file
	 * should only contain a single object written using 
	 * {@link #writeObject(String)}.  This uses basic Java 
	 * serialization.
	 * 
	 * @param dummy
	 * 		An object instance of the type which will be read in.  So
	 * 		if the method will de-serialize a Foo, this should be an
	 * 		instance of Foo
	 * @param filename
	 * 		The name of the file to read the object from
	 * 
	 * @return
	 * 		The object read from the file
	 * @throws ClassCastException
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	public static <T> T readObject(T dummy, String filename) 
		throws ClassCastException,ClassNotFoundException,IOException
	{
		// create the input stream
		FileInputStream fin = new FileInputStream(filename);
		ObjectInputStream input = new ObjectInputStream(fin);
		// read this object into a new object and close the stream
		T obj = (T)input.readObject();
		input.close();
		// return the object
		return obj;
	}
	
	/**
	 * Writes the given object to the file with the given filename.  
	 * This should be the only thing written to this file, if you 
	 * intend to retrieve the contents at some other time with a call 
	 * to {@link #readObject(String)}.  This uses basic Java 
	 * serialization.
	 * 
	 * @param obj
	 * 		The object to serialize
	 * @param filename
	 * 		The name of the file to write to
	 * @throws IOException
	 */
	public static void writeObject(Object obj, String filename) 
		throws IOException
	{
		// create the output stream
		FileOutputStream fout = new FileOutputStream(filename);
		ObjectOutputStream output = new ObjectOutputStream(fout);
		// write this object and close the stream
		output.writeObject(obj);
		output.close();
	}
}
